<template>
  <div class="plot-player" v-if="visible">
    <!-- 背景遮罩 -->
    <div class="plot-overlay" @click="handleSkip"></div>
    
    <!-- 剧情容器 -->
    <div class="plot-container">
      <!-- 章节标题 -->
      <div class="chapter-title" v-if="showTitle">
        <h2>{{ chapterName }}</h2>
        <div class="title-divider"></div>
      </div>
      
      <!-- 剧情文本区域 -->
      <div class="plot-content">
        <!-- 角色头像 -->
        <div class="character-avatar" v-if="currentCharacter">
          <img :src="currentCharacter.avatar" :alt="currentCharacter.name" />
          <div class="character-name">{{ currentCharacter.name }}</div>
        </div>
        
        <!-- 对话框 -->
        <div class="dialogue-box">
          <div class="dialogue-text" ref="dialogueText">
            {{ displayText }}
          </div>
          
          <!-- 继续提示 -->
          <div class="continue-hint" v-if="textComplete && !isLastDialogue">
            <span class="hint-text">点击继续</span>
            <div class="hint-arrow">▶</div>
          </div>
        </div>
      </div>
      
      <!-- 控制按钮 -->
      <div class="plot-controls">
        <button class="control-btn skip-btn" @click="handleSkip">
          跳过剧情
        </button>
        <button class="control-btn auto-btn" @click="toggleAuto" :class="{ active: autoPlay }">
          {{ autoPlay ? '停止自动' : '自动播放' }}
        </button>
        <button class="control-btn next-btn" @click="nextDialogue" v-if="textComplete">
          {{ isLastDialogue ? '完成' : '下一句' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { getChapterPlot } from '@/api/mainquest'

export default {
  name: 'PlotPlayer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    chapterId: {
      type: Number,
      required: true
    },
    autoStart: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 章节信息
      chapterName: '',
      plotData: null,
      
      // 对话控制
      currentDialogueIndex: 0,
      displayText: '',
      textComplete: false,
      typewriterTimer: null,
      
      // 播放控制
      autoPlay: false,
      autoTimer: null,
      showTitle: true,
      
      // 角色信息
      currentCharacter: null,
      
      // 配置
      typewriterSpeed: 50, // 打字机效果速度(ms)
      autoPlayDelay: 2000, // 自动播放延迟(ms)
    }
  },
  computed: {
    isLastDialogue() {
      return this.plotData && this.currentDialogueIndex >= this.plotData.dialogues.length - 1
    }
  },
  watch: {
    visible(newVal) {
      if (newVal && this.autoStart) {
        this.startPlot()
      } else if (!newVal) {
        this.resetPlot()
      }
    },
    chapterId() {
      if (this.visible) {
        this.startPlot()
      }
    }
  },
  methods: {
    // 开始播放剧情
    async startPlot() {
      try {
        this.showTitle = true
        const response = await getChapterPlot(this.chapterId)
        
        if (response.code === 1) {
          this.chapterName = response.data.chapter_name
          this.plotData = this.parseOpeningStory(response.data.opening_story)
          
          // 显示章节标题2秒后开始对话
          setTimeout(() => {
            this.showTitle = false
            this.startDialogue()
          }, 2000)
        } else {
          this.$emit('error', response.msg || '获取剧情数据失败')
        }
      } catch (error) {
        console.error('获取剧情数据失败:', error)
        this.$emit('error', '网络错误，请重试')
      }
    },
    
    // 解析开场剧情文本
    parseOpeningStory(storyText) {
      // 简单解析剧情文本，实际项目中可能需要更复杂的解析逻辑
      const dialogues = storyText.split('\n').filter(line => line.trim())
      
      return {
        dialogues: dialogues.map((text, index) => ({
          id: index,
          text: text.trim(),
          character: this.getCharacterForDialogue(text),
          speed: this.typewriterSpeed
        }))
      }
    },
    
    // 根据对话内容获取角色信息
    getCharacterForDialogue(text) {
      // 简单的角色识别逻辑，实际项目中可能需要更复杂的逻辑
      if (text.includes('旁白') || text.includes('系统')) {
        return {
          name: '旁白',
          avatar: '/static/images/narrator.png'
        }
      }
      
      return {
        name: '主角',
        avatar: '/static/images/protagonist.png'
      }
    },
    
    // 开始对话
    startDialogue() {
      if (!this.plotData || this.plotData.dialogues.length === 0) {
        this.completePlot()
        return
      }
      
      this.currentDialogueIndex = 0
      this.showCurrentDialogue()
    },
    
    // 显示当前对话
    showCurrentDialogue() {
      if (!this.plotData || this.currentDialogueIndex >= this.plotData.dialogues.length) {
        return
      }
      
      const dialogue = this.plotData.dialogues[this.currentDialogueIndex]
      this.currentCharacter = dialogue.character
      this.displayText = ''
      this.textComplete = false
      
      // 打字机效果
      this.startTypewriter(dialogue.text, dialogue.speed)
    },
    
    // 打字机效果
    startTypewriter(text, speed = this.typewriterSpeed) {
      this.clearTypewriter()
      
      let index = 0
      this.typewriterTimer = setInterval(() => {
        if (index < text.length) {
          this.displayText += text[index]
          index++
        } else {
          this.textComplete = true
          this.clearTypewriter()
          
          // 自动播放模式下自动进入下一句
          if (this.autoPlay) {
            this.autoTimer = setTimeout(() => {
              this.nextDialogue()
            }, this.autoPlayDelay)
          }
        }
      }, speed)
    },
    
    // 清除打字机定时器
    clearTypewriter() {
      if (this.typewriterTimer) {
        clearInterval(this.typewriterTimer)
        this.typewriterTimer = null
      }
    },
    
    // 清除自动播放定时器
    clearAutoTimer() {
      if (this.autoTimer) {
        clearTimeout(this.autoTimer)
        this.autoTimer = null
      }
    },
    
    // 下一句对话
    nextDialogue() {
      this.clearAutoTimer()
      
      if (!this.textComplete) {
        // 如果文字还在播放，直接显示完整文字
        this.clearTypewriter()
        const dialogue = this.plotData.dialogues[this.currentDialogueIndex]
        this.displayText = dialogue.text
        this.textComplete = true
        return
      }
      
      if (this.isLastDialogue) {
        this.completePlot()
      } else {
        this.currentDialogueIndex++
        this.showCurrentDialogue()
      }
    },
    
    // 切换自动播放
    toggleAuto() {
      this.autoPlay = !this.autoPlay
      
      if (!this.autoPlay) {
        this.clearAutoTimer()
      } else if (this.textComplete && !this.isLastDialogue) {
        this.autoTimer = setTimeout(() => {
          this.nextDialogue()
        }, this.autoPlayDelay)
      }
    },
    
    // 跳过剧情
    handleSkip() {
      this.completePlot()
    },
    
    // 完成剧情播放
    completePlot() {
      this.resetPlot()
      this.$emit('complete')
    },
    
    // 重置剧情状态
    resetPlot() {
      this.clearTypewriter()
      this.clearAutoTimer()
      
      this.chapterName = ''
      this.plotData = null
      this.currentDialogueIndex = 0
      this.displayText = ''
      this.textComplete = false
      this.autoPlay = false
      this.showTitle = true
      this.currentCharacter = null
    }
  },
  
  beforeDestroy() {
    this.resetPlot()
  }
}
</script>

<style scoped>
.plot-player {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.plot-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(5px);
}

.plot-container {
  position: relative;
  width: 90%;
  max-width: 800px;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
  border: 2px solid #ffd700;
}

.chapter-title {
  text-align: center;
  margin-bottom: 30px;
  animation: fadeInDown 1s ease-out;
}

.chapter-title h2 {
  color: #ffd700;
  font-size: 28px;
  font-weight: bold;
  margin: 0 0 15px 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.title-divider {
  width: 100px;
  height: 3px;
  background: linear-gradient(90deg, transparent, #ffd700, transparent);
  margin: 0 auto;
}

.plot-content {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 30px;
  min-height: 200px;
}

.character-avatar {
  flex-shrink: 0;
  text-align: center;
  animation: fadeInLeft 0.5s ease-out;
}

.character-avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid #ffd700;
  object-fit: cover;
}

.character-name {
  margin-top: 10px;
  color: #ffd700;
  font-size: 14px;
  font-weight: bold;
}

.dialogue-box {
  flex: 1;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px;
  border: 1px solid rgba(255, 215, 0, 0.3);
  position: relative;
  animation: fadeInRight 0.5s ease-out;
}

.dialogue-text {
  color: #ffffff;
  font-size: 16px;
  line-height: 1.6;
  min-height: 60px;
  word-wrap: break-word;
}

.continue-hint {
  position: absolute;
  bottom: 10px;
  right: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
  color: #ffd700;
  font-size: 12px;
  animation: pulse 1.5s infinite;
}

.hint-arrow {
  font-size: 10px;
}

.plot-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.control-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 25px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 80px;
}

.skip-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.skip-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.auto-btn {
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
  border: 1px solid rgba(255, 215, 0, 0.5);
}

.auto-btn.active {
  background: #ffd700;
  color: #1a1a2e;
}

.auto-btn:hover {
  background: rgba(255, 215, 0, 0.3);
  transform: translateY(-2px);
}

.next-btn {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #1a1a2e;
  border: none;
}

.next-btn:hover {
  background: linear-gradient(135deg, #ffed4e, #ffd700);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
}

/* 动画效果 */
@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .plot-container {
    width: 95%;
    padding: 20px;
  }
  
  .chapter-title h2 {
    font-size: 24px;
  }
  
  .plot-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .character-avatar {
    margin-bottom: 15px;
  }
  
  .dialogue-text {
    font-size: 14px;
  }
  
  .plot-controls {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .control-btn {
    padding: 8px 16px;
    font-size: 12px;
    min-width: 70px;
  }
}
</style>